/* eslint-disable consistent-return */
/* eslint-disable array-callback-return */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  DownloadOutlined,
  DownOutlined,
  UpOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import {
  Card,
  Button,
  Input,
  Select,
  Row,
  Form,
  Col,
  Modal,
  DatePicker,
  Menu,
  Dropdown,
  message,
} from 'antd';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import downloadFile from '@/utils/utils'; // 导出excel
import styles from '@/utils/utils.less';
import Authorized from '@/utils/Authorized';
import HOCSelect from '@/components/AntDesign/Select';
import TextOverFlow from '../../components/TextOverFlow';
import Supplier from '../../components/Supplier'; // 获取字典签约方
import Customer from '../../components/CustomerWithState'; // 获取字典客户名称

const { Option } = Select;
const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { confirm } = Modal;

@connect(({ publicdata, empsearch, loading }) => ({
  dictCode: publicdata.dictCode,
  data: empsearch.data,
  loading: loading.models.empsearch,
  formFieldsValue: empsearch.formFieldsValue,
  expandForm: empsearch.expandForm,
  valuesArr: empsearch.valuesArr,
  respUserList: empsearch.respUserList,
}))
class BasicList extends PureComponent {
  formRef = React.createRef();

  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [],
      selectedRows: [],
      formValues: {},
    };
    // 表单布局
    this.formItemLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
  }

  componentDidMount = () => {
    const { dispatch } = this.props;
    // 获取字典状态
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['SEND_STATUS'],
    });
    // 获取所属客服列表数据
    dispatch({
      type: 'empsearch/fetchRespUserList',
      payload: {},
    });
    this.getInitialList();
  };

  getInitialList = () => {
    const {
      data: { pagination },
      dispatch,
      location,
      formFieldsValue,
    } = this.props;
    if (location.queryParam) {
      dispatch({
        type: 'empsearch/updateModelData',
        payload: { formFieldsValue: location.queryParam, expandForm: true },
      });
    }
    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      pagination.current,
      pagination.pageSize
    );
  };

  /**
   * 点击查询按钮
   */
  searchBtnList = async() => {
    const { valuesArr, dispatch } = this.props;
    const values = await this.formRef.current.validateFields(valuesArr);
    await dispatch({
      type: 'empsearch/updateModelData',
      payload: {
        formFieldsValue: values,
      },
    });
    this.searchList(this.processFormData(values));
  };

  // 查询
  searchList = (formFieldsValue, currentPage = 1, pageSize = 10, isClear = true) => {
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }

    const { dispatch } = this.props;
    const pageArg = { currentPage, pageSize };
    const values = {
      ...formFieldsValue,
      pageArg,
    };

    dispatch({
      type: 'empsearch/updateModelData',
      payload: {
        values,
      },
    });

    dispatch({
      type: 'empsearch/fetchList',
      payload: values,
    });
    this.setState({ formValues: values });
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'empName' || key === 'idCode') {
        tempFieldsValue[key] = (tempFieldsValue[key] && tempFieldsValue[key].trim()) || null;
      }
      if (key === 'sendTime') {
        formFieldsValue.sendTimeStart =
          (tempFieldsValue.sendTime &&
            tempFieldsValue.sendTime[0] &&
            tempFieldsValue.sendTime[0].format('YYYY-MM-DD')) ||
          null;
        formFieldsValue.sendTimeEnd =
          (tempFieldsValue.sendTime &&
            tempFieldsValue.sendTime[1] &&
            tempFieldsValue.sendTime[1].format('YYYY-MM-DD')) ||
          null;
      }
      if (key === 'redEmpTime') {
        formFieldsValue.redEmpTimeStart =
          (tempFieldsValue.redEmpTime &&
            tempFieldsValue.redEmpTime[0] &&
            tempFieldsValue.redEmpTime[0].format('YYYY-MM-DD')) ||
          null;
        formFieldsValue.redEmpTimeEnd =
          (tempFieldsValue.redEmpTime &&
            tempFieldsValue.redEmpTime[1] &&
            tempFieldsValue.redEmpTime[1].format('YYYY-MM-DD')) ||
          null;
      }
      formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
      delete formFieldsValue.sendTime;
      delete formFieldsValue.redEmpTime;
    });
    return formFieldsValue;
  };

  // 展开收起
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'empsearch/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  // 重置
  resetSearch = async () => {
    const { dispatch } = this.props;
    await dispatch({
      type: 'empsearch/updateModelData',
      payload: { formFieldsValue: {} },
    });
    this.formRef.current.resetFields();
    this.formRef.current.setFieldsValue({ redEmpTime: null, sendTime: null });
    this.setState({
      selectedRowKeys:[],
      selectedRows:[]
    })
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { formFieldsValue } = this.props;
    this.searchList(
      this.processFormData(formFieldsValue),
      pagination.current,
      pagination.pageSize,
      false
    );
  };

  // 问题人员导出数据
  export = () => {
    const { selectedRowKeys } = this.state;
    if (!selectedRowKeys.length) {
      Modal.warning({
        title: '温馨提示',
        content: '如果不选择列表数据，则默认导出当前条件下所有数据',
        okText: '知道了',
        onOk: () => {
          this.exportExcel();
        },
      });
    } else {
      this.exportExcel();
    }
  };

  // 导出excel
  exportExcel = () => {
    const { formValues, selectedRowKeys } = this.state;
    delete formValues.pageArg;
    const params = {
      ...formValues,
      sendIdList: selectedRowKeys,
    };
    downloadFile(params, '/csApi/empSendQueryService/emp/export', 'POST');
  };

  // 锁定，解锁
  locked = () => {
    const {
      dispatch,
      data: {
        pagination: { current, pageSize, total },
      },
      formFieldsValue,
    } = this.props;
    const { selectedRowKeys, selectedRows } = this.state;
    if (selectedRowKeys.length === 0) {
      message.warning('请选择一条员工数据');
    } else {
      let flag = null;
      const lockStatusFirst = selectedRows[0].lockStatus;
      const status = [3, 4, 5];
      // 交集
      const intersection = selectedRows.filter(v => status.includes(v.sendStatus));
      if (intersection.length > 0) {
        message.warning('只有入职办理中和在职人员，可操作锁定/解锁');
        return false;
      }
      selectedRows.map(item => {
        if (lockStatusFirst !== item.lockStatus) {
          message.warning('选择人员通过存在已锁定和未锁定的人员，请选择相同类型人员操作');
          flag = 2;
        } else {
          flag = 1;
        }
      });
      if (flag === 1) {
        confirm({
          icon: <QuestionCircleOutlined />,
          title: selectedRows[0].lockStatus === 1 ? '解锁减员' : '锁定减员',
          content:
            selectedRows[0].lockStatus === 1
              ? '解锁之后，可操作减员，减员之后生育和工伤可能无法报销，是否确认解锁？'
              : '锁定之后，此员工无法减员，是否确认锁定？',
          okText: '确定',
          cancelText: '取消',
          style: { top: 200 },
          onOk: () => {
            dispatch({
              type: 'empsearch/locked',
              payload: {
                sendIdList: selectedRowKeys,
                lockStatus: selectedRows[0].lockStatus === 1 ? 2 : 1,
              },
            }).then(res => {
              if (res.success) {
                const selectedLen = 1;
                if (current > 1 && (total % pageSize === selectedLen || pageSize === selectedLen)) {
                  this.searchList(this.processFormData(formFieldsValue), current - 1, pageSize);
                } else {
                  this.searchList(this.processFormData(formFieldsValue), current, pageSize);
                }
                this.setState({ selectedRowKeys: [], selectedRows: [] });
                message.success(`${selectedRows[0].lockStatus === 1 ? '解锁' : '锁定'}成功！`);
              } else {
                message.warning(`${res.message || '服务器端错误'}`);
              }
            });
          },
          onCancel: () => {
            this.setState({ selectedRowKeys: [], selectedRows: [] });
          },
        });
      }
    }
  };

  renderSimpleForm() {
    const {
      formFieldsValue,
    } = this.props;
    return (
      <Form ref={this.formRef} layout="inline" initialValues={formFieldsValue}>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="员工姓名" name="empName">
              <Input placeholder="请输入" />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="证件号" name="idCode">
              <Input placeholder="请输入" />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={this.searchBtnList}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      formFieldsValue,
      dictCode,
      respUserList,
    } = this.props;
    return (
      <Form ref={this.formRef} layout="inline" initialValues={formFieldsValue}>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="员工姓名" name="empName">
              <Input placeholder="请输入" />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="证件号" name="idCode">
              <Input placeholder="请输入" />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="客户名称" name="custId">
              <Customer allowClear />
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="状态" name="sendStatus">
              <HOCSelect placeholder="请选择" allowClear>
                {dictCode.SEND_STATUS &&
                  dictCode.SEND_STATUS.map(item => (
                    <Option key={item.itemCode}>{item.itemName}</Option>
                  ))}
              </HOCSelect>
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="签约方" name="sendCorp">
              <Supplier allowClear />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="派单时间" name="sendTime">
              <RangePicker
                placeholder={['派单开始日期', '派单结束日期']}
                style={{ width: '100%' }}
                format="YYYY-MM-DD"
              />
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="减员时间" name="redEmpTime">
              <RangePicker
                placeholder={['减员开始日期', '减员结束日期']}
                style={{ width: '100%' }}
                format="YYYY-MM-DD"
              />
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="所属客服" {...this.formItemLayout} name="primId">
              <HOCSelect
                placeholder="请输入关键字检索"
                style={{ width: '100%' }}
                showSearch
                optionFilterProp="children"
                allowClear
              >
                {respUserList.map(item => (
                  <Option key={item.userId} title={item.userName}>
                    {item.userName}
                  </Option>
                  ))}
              </HOCSelect>
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span style={{ float: 'right', marginBottom: 24 }}>
                <Button type="primary" onClick={this.searchBtnList}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起 <UpOutlined />
                </a>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const { selectedRowKeys, selectedRows } = this.state;
    const { data, loading } = this.props;
    const moreMenu = (
      <Menu>
        <Menu.Item key="locked" onClick={this.locked}>
          锁定/解锁
        </Menu.Item>
      </Menu>
    );
    const columns = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '证件号',
        dataIndex: 'idCode',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '入职日期',
        dataIndex: 'entryDate',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => text || '--',
      },
      {
        title: '离职日期',
        dataIndex: 'evaDate',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => text || '--',
      },
      {
        title: '状态',
        dataIndex: 'sendStatusName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '服务类型',
        dataIndex: 'sendTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        align: 'center',
      },
      {
        title: '签约方',
        dataIndex: 'sendCorpName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '所属客服',
        dataIndex: 'primName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val && val) || '--',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a
              onClick={() =>
                router.push(`/customservicemanage/empsearch/detail?sendId=${record.sendId}`)
              }
            >
              查看
            </a>
          </span>
        ),
      },
    ];
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card className={styles.tableCard}>
          <Row style={{ marginBottom: 16 }}>
            <Authorized authority="cs:empSendQueryService:emp/export" noMatch={null}>
              <Button
                type="primary"
                style={{ marginRight: 8 }}
                icon={<DownloadOutlined />}
                onClick={this.export}
              >
                导出
              </Button>
            </Authorized>
            <Authorized authority="cs:empSendQueryService:lock" noMatch={null}>
              <Dropdown overlay={moreMenu}>
                <Button>
                  更多
                  <DownOutlined />
                </Button>
              </Dropdown>
            </Authorized>
          </Row>
          <StandardTable
            selectedRows={selectedRows}
            selectedRowKeys={selectedRowKeys}
            loading={loading}
            data={data}
            rowKey="sendId"
            columns={columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}
export default BasicList;
